import JavaBean.User;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.*;
import java.io.*;
import java.util.HashMap;
import java.util.Map;


/**
 * @author Sai
 * Created by Sai on 2019-03-03.
 */
@SuppressWarnings("Duplicates")
@WebServlet(urlPatterns = {"/login/dgut"})
public class LoginServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws  IOException {
        int flag=0;
        LoginController loginController=new LoginController();
        Map<String,String> userinfo = new HashMap<String,String>();
        userinfo = loginController.login(request,response);
        String username = userinfo.get("username");
        System.out.println(username);
        String name = userinfo.get("name");
        String PersonMessage=null;
        String root = System.getProperty("user.dir");
        String FileName="Usermessage.txt";
        String filepath = root+ File.separator+FileName;
        FileReader fd = new FileReader(filepath);
        BufferedReader reader = new BufferedReader(fd);
        if(username==null)
            return;
        while((PersonMessage = reader.readLine())!=null) {
            String message[] = PersonMessage.split(" ");
            if (message[4].equals(username)) {
                HttpSession session = request.getSession();
                User userr = new User(message[0],message[1],message[2],message[3],message[4]);
                session.setAttribute("user",userr);
                flag=1;
            }
        }
        fd.close();
        reader.close();
        if(flag==0){
            HttpSession session = request.getSession();
            FileWriter fd1 = new FileWriter(filepath,true);
            BufferedWriter writer = new BufferedWriter(fd1);
            String Email ="test@qq.com";
            String img = "picture/"+username+".jpg";
            writer.write(name + " " + Email + " " + "123456" + " " + img + " " + username + "\n");
            writer.flush();
            writer.close();
            User userr = new User( name, Email,"123456",img,username);
            session.setAttribute("user",userr);
            fd1.close();
            writer.close();
        }
        response.sendRedirect("/UserPage.jsp");
    }
}
